<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" placeholder="请输入关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">添加管理员</el-button>
    </div>

    <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;">
      <el-table-column label="ID" prop="id" align="center" width="65">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" min-width="80px">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="登录名称" min-width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.userLoginName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="密码" min-width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.userLoginPwd }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="id" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sys_role && scope.row.sys_role.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后登录时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updatedAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 400px; margin-left:50px;">

        <el-form-item label="管理员名称">
          <el-input :autosize="{ minRows: 2, maxRows: 4}" v-model="temp.userName" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="所属角色" prop="type">
          <el-select v-model="temp.role_id" class="filter-item" placeholder="请选择">
            <el-option v-for="item in roleListData" :key="item.id" :label="item.roleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="登录名称" prop="title">
          <el-input v-model="temp.userLoginName" />
        </el-form-item>
        <el-form-item label="密码" prop="title">
          <el-input v-model="temp.userLoginPwd" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import {
	fetchManagerAjax,
	addManagerAjax,
	updateManagerAjax,
	delManagerAjax,
	fetchRoleAjax
} from "@/api/authority";
import waves from "@/directive/waves"; // Waves directive
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

const calendarTypeOptions = [
	{ key: "CN", display_name: "China" },
	{ key: "US", display_name: "USA" },
	{ key: "JP", display_name: "Japan" },
	{ key: "EU", display_name: "Eurozone" }
];

export default {
	name: "ManagerList",
	components: { Pagination },
	directives: { waves },
	filters: {
		parseRole(role) {
			return '超级管理员'
		}
	},
	data() {
		return {
			tableKey: 0,
			list: null,
			total: 0,
			listLoading: true,
			listQuery: {
				pageNum: 1,
				pageSize: 10
			},
			calendarTypeOptions,
			temp: {
				role_id: "",
				userName: "",
				userLoginName: "",
				userLoginPwd: ""
			},
			dialogFormVisible: false,
			dialogStatus: "",
			textMap: {
				update: "编辑",
				create: "新增门店"
			},
			roleListData: null,
			dialogPvVisible: false,
			pvData: [],
			rules: {
				// type: [
				// 	{
				// 		required: true,
				// 		message: "type is required",
				// 		trigger: "change"
				// 	}
				// ],
				// timestamp: [
				// 	{
				// 		type: "date",
				// 		required: true,
				// 		message: "timestamp is required",
				// 		trigger: "change"
				// 	}
				// ],
				// title: [
				// 	{
				// 		required: true,
				// 		message: "title is required",
				// 		trigger: "blur"
				// 	}
				// ]
			},
			downloadLoading: false
		};
	},
	created() {
		this.getList();
	},
	methods: {
		getList() {
			this.listLoading = true;
			fetchManagerAjax(this.listQuery).then(response => {
				this.list = response.data.data.pageData;
				this.total = response.data.data.maxCount;
				this.listLoading = false;
			});
		},
		handleFilter() {
			this.listQuery.page = 1;
			this.getList();
		},
		resetTemp() {
			this.temp = {
				role_id: "",
				userName: "",
				userLoginName: "",
				userLoginPwd: ""
			};
		},
		getRoleList() {
			this.listLoading = true;
			fetchRoleAjax().then(response => {
				this.roleListData = response.data.data;
				// this.total = response.data.data.maxPage;
				this.listLoading = false;
			});
		},
		handleCreate() {
			this.resetTemp();
			this.dialogStatus = "create";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
			this.getRoleList();
		},
		createData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					addManagerAjax(this.temp).then(() => {
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "创建成功",
							type: "success",
							duration: 2000
						});
					});
				}
			});
		},
		handleUpdate(row) {
			this.temp = Object.assign({}, row); // copy obj
			this.temp.timestamp = new Date(this.temp.timestamp);
			this.dialogStatus = "update";
			this.dialogFormVisible = true;
			this.$nextTick(() => {
				this.$refs["dataForm"].clearValidate();
			});
			this.getRoleList();
		},
		updateData() {
			this.$refs["dataForm"].validate(valid => {
				if (valid) {
					const tempData = Object.assign({}, this.temp);
					tempData.timestamp = +new Date(tempData.timestamp); // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
					updateManagerAjax(tempData).then(() => {
						for (const v of this.list) {
							if (v.id === this.temp.id) {
								const index = this.list.indexOf(v);
								this.list.splice(index, 1, this.temp);
								break;
							}
						}
						this.dialogFormVisible = false;
						this.$notify({
							title: "成功",
							message: "更新成功",
							type: "success",
							duration: 2000
						});
					});
				}
			});
		},
		handleDelete(row) {
			this.$confirm('确认删除该条数据吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				delManagerAjax(row).then((res) => {
				// const index = this.list.indexOf(row);
				// this.list.splice(index, 1);
				if (res.data.code !== 0 || res.data.data.length < 0) {
						this.$message({
							message: '删除失败',
							type: 'error',
							duration: 5 * 1000
						})
						return;
					}
					this.$notify({
						title: "成功",
						message: "删除成功",
						type: "success",
						duration: 2000
					});
					this.getList();
				});
			})
		}
	}
};
</script>
